<?php
/**
 * Hy - 系统后台公共类
 *
 * Copyright (c) 2013 YinHailin All rights reserved.
 * @Author: YinHailin
 * @Authorize: Boren Network
 * @Created by YinHailin at 2013-11-20
 */

defined('LY_VERSION') or exit();

class PublicMod extends BasicMod {

  /* 公共方法 */
  public function GetGlobal() {
    header("Content-Type:text/html; charset=utf-8");  //字符编码处理
    $this->Assign('activeUrl', get_active_url());  //输出当前页面URL
    if (deep_htmlspecialchars($_GET['url'] != '')) {  //如果返回URL不为空，则输出返回地址
      $this->Assign('backUrl', urlencode(deep_htmlspecialchars($_GET['url'])));
    }
    //全局程序插槽
    rabbet('global_func', 'global');
    $this->Assign('pageTitle', C('SYS_NAME').' '.C('SYS_VERSION'));  //输出Title
  }

  /*
   * 获取用户登录状态
   * @param boolean $isLoginPage 当前是登录页
   * @return string
   */
  public function CheckLogin($isLoginPage = false) {
    $activeUser = $this->GetActiveUser();
    //配置信息
    $config = array('keyName' => C('ADMIN_NAME'), 'tokenTimeout' => C('ADMIN_TOKEN_TIMEOUT'), 'sidTimeout'=>C('ADMIN_SID_TIMEOUT'), 'thisIp'=>C('ADMIN_THIS_IP'), thisBrowser=>C('ADMIN_THIS_BROWSER'));
    //用户信息
    $user = array('key' => $activeUser['id'], 'token' => $activeUser['active_token'], 'sid' => $activeUser['active_sid'], 'time' => $activeUser['active_time'], 'ip' => $activeUser['last_login_ip']);
    $loginStatus = parent::SetLogin(3, $user, $config);
    switch ($loginStatus) {
      case '011' :
        if (!$isLoginPage) {
          echo '<script type="text/javascript">alert("登录超时，请重新登录");top.location.replace("/admin.php?m=index&a=login");</script>';
          exit();
        }
        break;
      case '101' :
        $this->SetAdminLogin(2, $activeUser['id']);
        break;
      case '001' :
        if (!$isLoginPage) {
          echo '<script type="text/javascript">alert("系统繁忙，请稍后再试");top.location.replace("/admin.php?m=index&a=login");</script>';
          exit();
        }
        break;
      case '100' :
        echo '<script type="text/javascript">if (confirm("账号已在另一地点登录，是否需要强行登录？")) { location.replace("/admin.php?m=index&a=force&url='.get_active_url().'");} else { top.location.replace("/admin.php?m=index&a=login");}</script>';
        exit();
        break;
      case '110' :
        echo '<script type="text/javascript">if (confirm("账号已在另一浏览器登录，是否需要强行登录？")) { location.replace("/admin.php?m=index&a=force&url='.get_active_url().'");} else { top.location.replace("/admin.php?m=index&a=login");}</script>';
        exit();
        break;
      case '111' :
        if ($isLoginPage) {
          echo '<script type="text/javascript">top.location.replace("/admin.php?m=index&a=admin");</script>';
        }
        break;
    }
  }

  /*
   * 获取当前用户信息
   * @return array | null
   */
  public function GetActiveUser() {
    static $_activeUser = null;
    if (!is_null($_activeUser)) {
      //数据存在则直接返回
      return $_activeUser;
    } else {
      //查询数据库
      $objAdmin = M(self::$dataAdmin);
      if (isset($_SESSION[C('ADMIN_NAME')]) && isset($_COOKIE[C('ADMIN_NAME')]).'_token') {
        $find = $objAdmin->Alias('AS d')->Field('d.*, g.group_name')->Join(get_real_table(self::$dataAdminGroup).' AS g ON g.id = d.group_id')->Where('d.id = '.intval($_SESSION[C('ADMIN_NAME')]['key']))->Find();
        $find = deep_htmlspecialchars_decode($find);
        if ($find) {
          $objAdmin->Where('id = '.$find['id'])->SetField('active_time', time());
          $_activeUser = $find;
          unset($_activeUser['password']);
        } else {
          $_activeUser = null;
        }
      }
      if (isset($_COOKIE[C('ADMIN_NAME')])) {
        //配置信息
        $config = array('keyName' => C('ADMIN_NAME'), 'tokenTimeout' => C('ADMIN_TOKEN_TIMEOUT'), 'sidTimeout'=>C('ADMIN_SID_TIMEOUT'), 'thisIp'=>C('ADMIN_THIS_IP'), thisBrowser=>C('ADMIN_THIS_BROWSER'));
        $id = intval($_COOKIE[C('ADMIN_NAME').'_key']);
        $token = $objAdmin->Where('status = "1" AND id = '.$id)->GetField('active_token');
        if ($token) {
          parent::SetLogin(2, array('token'=>$token), $config);
          $_activeUser = $this->GetActiveUser();
        } else {
          $_activeUser = null;
        }
      }
    }
    return $_activeUser;
  }

  /*
   * 进行用户登录
   * @param integer $type 登录方式 1=密码登录 2=Cookie登录 其它表示退出登录
   * @param integer $id 用户ID
   * @return string
   */
  public function SetAdminLogin($type, $id = '') {
    if ($type != 1 && $type != 2) { $type = 0;}  //取值限定

    $objAdmin = M(self::$dataAdmin);

    //数据库写入
    $user = $objAdmin->Where('id = '.intval($id))->Find();
    if (!$user) { return '0100';}
    if (intval($type) === 2) {
      $data['active_sid'] = $_COOKIE[C('ADMIN_NAME').'_sid'];
    } else {
      $data['active_sid'] = md5(rand(1000, 9999).'_hy');
    }
    $data['active_time'] = time();
    $data['last_login_ip'] = get_client_ip();
    $data['last_login_time'] = $data['active_time'];
    $data['login_times'] = array('exp', 'login_times + 1');
    if ($user['active_token'] == '') {
      $data['active_token'] = md5(rand(1000, 9999).'_hy');
      $user['active_token'] = $data['active_token'];
    }
    if ($type > 0) { $objAdmin->Where('id = '.intval($id))->Save($data);}
    //配置信息
    $config = array('keyName' => C('ADMIN_NAME'), 'tokenTimeout' => C('ADMIN_TOKEN_TIMEOUT'), 'sidTimeout'=>C('ADMIN_SID_TIMEOUT'), 'thisIp'=>C('ADMIN_THIS_IP'), 'thisBrowser'=>C('ADMIN_THIS_BROWSER'));
    //用户信息
    $user = array('key' => $user['id'], 'token' => $user['active_token'], 'sid' => $data['active_sid'], 'time' => $data['active_time'], 'ip' => $data['last_login_ip']);
    return parent::SetLogin($type, $user, $config);
  }

  /*
   * 检查管理员权限
   * @param string $identifier 权限标识
   */
  public function CheckPurview($identifier) {
    $activeUser = $this->GetActiveUser();
    if (!in_array($identyfy, explode(',', $activeUser['purview']))) {
      $this->Error('权限不足，不能进行该项操作');
    }
  }
}